package com.dps.omc.mq.consumer.impl;

import com.dps.omc.model.Task;
import com.dps.omc.model.User;
import com.dps.omc.mq.consumer.Tasker;
import com.dps.omc.service.ILogFileService;
import com.dps.omc.service.ITaskService;
import com.dps.omc.task.message.EnumMsgType;
import com.dps.omc.task.message.EnumTaskState;
import com.dps.omc.task.message.TaskMessage;
import com.dps.omc.utils.ErrorAnalyzer;
import com.dps.common.utils.DateUtils;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.jms.JMSException;
import javax.jms.TextMessage;

/**
 * Created by lip on 2016-01-19.
 */

@Component
public class AgentBackTasker implements Tasker{

    private static final Integer RETURN_MSG_MAXSIZE = 2000;

    private static final Logger logger = LoggerFactory.getLogger(AgentBackTasker.class);

    @Autowired
    private ITaskService taskService;
    @Autowired
    private ErrorAnalyzer errorAnalyzer;
    @Autowired
    private ILogFileService logFileService;

    @Override
    public void send(JSONObject jsonObject) {

    }

    @Override
    public void receive(TextMessage textMessage) {

        User user = new User();
        user.setRealName("SYS");
        try {
            TaskMessage taskMessage = this.getTaskMessage(textMessage.getText());
            String taskId = taskMessage.getTaskId();
            Task task = taskService.fetch(taskId);
//            task.setStatus(taskMessage.getTaskState());
            task.setStatus(this.getTaskState(taskMessage));

            String returnMsg = taskMessage.getReturnMsg();
            Integer msgMaxSize = RETURN_MSG_MAXSIZE;
            String msg = returnMsg.length()>msgMaxSize?returnMsg.substring(0,msgMaxSize):returnMsg;
            this.uploadLog(taskId,returnMsg);

            task.setReturnMsg(msg);
            task.setEndDate(DateUtils.now());
            taskService.update(task,user);
        } catch (JMSException e) {
            logger.error(e.toString());
        }
    }

    //过长的日志上传到文件服务器里
    private void uploadLog(String taskId,String returnMsg)
    {
        if(returnMsg.length()>RETURN_MSG_MAXSIZE)
        {
            new Thread(new UploadLogThread(taskId,returnMsg,taskService,logFileService)).start();
        }
    }

    private EnumTaskState getTaskState(TaskMessage taskMessage)
    {
        if(errorAnalyzer.analyse(taskMessage.getReturnMsg()))
        {
            return EnumTaskState.FAIL;
        }
        return taskMessage.getTaskState();
    }

    private TaskMessage getTaskMessage(String msg)
    {
        JSONObject jsonObject = JSONObject.fromObject(msg);
        JSONObject obj = jsonObject.getJSONObject("taskMessage");
        TaskMessage tm = new TaskMessage();
        tm.setTaskId(obj.getString("taskId"));
        tm.setCmdShell(obj.getString("cmdShell"));
        tm.setAgentId(obj.getString("agentId"));
        tm.setClientIp(obj.getString("clientIp"));
        tm.setSysUser(obj.getString("sysUser"));
        tm.setSysPass(obj.getString("sysPass"));
        tm.setMsgType(EnumMsgType.valueOf(obj.getString("msgType")));
        tm.setReturnMsg(obj.getString("returnMsg"));
        tm.setTaskState(EnumTaskState.valueOf(obj.getString("taskState")));
        tm.setServerIp(obj.getString("serverIp"));
        tm.setServerUser(obj.getString("serverUser"));
        tm.setServerPass(obj.getString("serverPass"));
        tm.setServerConn(obj.getString("serverConn").equals("true")?true:false);
        return tm;
    }


}
